from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.db import connection
from django.utils.dateparse import parse_date
from django.urls import reverse
from datetime import datetime
from django.shortcuts import render
from django.http import JsonResponse
import json
from urllib.parse import unquote

# 定义列名列表
COLUMN_NAMES = [
    '检验单号', '检验日期', '存货编码', '存货名称', '规格型号',
    '品牌', '供应商编码', '供应商名称', '批号', '生产日期', '合格数量', '不良数量'
]

def index(request):
    with connection.cursor() as cursor:
        cursor.execute('SELECT * FROM CHECK_VIEW')
        datas = cursor.fetchall()

    # 将元组列表转换为字典列表
    datas = [dict(zip(COLUMN_NAMES, data)) for data in datas]

    # 获取用户的排序选择，默认为 'asc'（从小到大）
    order = request.GET.get('order', 'asc')

    with connection.cursor() as cursor:
        cursor.execute('SELECT DISTINCT 批号 FROM CHECK_VIEW')
        distinct_batches = [row[0] for row in cursor.fetchall()]  # 这里得到的是批号列表，而不是字典

    # 根据用户的排序选择来排序 '批号'
    if order == 'desc':
        distinct_batches.sort(reverse=True)  # 由于是列表，不需要 key 函数
    else:
        distinct_batches.sort()  # 默认升序排序，可以省略不写



    template = loader.get_template('index.html')
    context = {
        'datas': datas,
        'distinct_batches': distinct_batches,
    }
    return HttpResponse(template.render(context, request))

# def filter_by_date(request):
#     if request.method == 'POST':
#         date = request.POST.get('date')
#         selected_date = date  # 保存用户选择的日期
#         if date:
#             parsed_date = datetime.strptime(date, '%Y-%m-%d').date()
#             with connection.cursor() as cursor:
#                 cursor.execute('SELECT * FROM CHECK_VIEW WHERE 检验日期 = %s', [parsed_date])
#                 datas = cursor.fetchall()
#             datas = [dict(zip(COLUMN_NAMES, data)) for data in datas]
#         else:
#             datas = []
#     else:
#         return HttpResponseRedirect(reverse('index'))

#     template = loader.get_template('index.html')
#     context = {
#         'datas': datas,
#         'selected_date': selected_date  # 添加选择的日期到上下文
#     }
#     return HttpResponse(template.render(context, request))

def filter_by_date(request):
    if request.method == 'POST':
        date = request.POST.get('date')
        if date:
            parsed_date = datetime.strptime(date, '%Y-%m-%d').date()
            with connection.cursor() as cursor:
                cursor.execute('SELECT * FROM CHECK_VIEW WHERE 检验日期 = %s', [parsed_date])
                datas = cursor.fetchall()
            datas = [dict(zip(COLUMN_NAMES, data)) for data in datas]
        else:
            datas = []
    else:
        return HttpResponseRedirect(reverse('index'))

    template = loader.get_template('index.html')
    context = {
        'datas': datas,
    }
    return HttpResponse(template.render(context, request))




def filter_by_batch(request):
    if request.method == 'POST':
        batch = request.POST.get('批号')
        if batch:
            with connection.cursor() as cursor:
                cursor.execute('SELECT * FROM CHECK_VIEW WHERE 批号 = %s', [batch])
                datas = cursor.fetchall()
            datas = [dict(zip(COLUMN_NAMES, data)) for data in datas]
        else:
            datas = []
    else:
        return HttpResponseRedirect(reverse('index'))

    template = loader.get_template('index.html')
    context = {
        'datas': datas,
    }
    return HttpResponse(template.render(context, request))

def selected_data(request):
    if request.method == 'POST':
        # 从请求中获取数据
        selected_data_array = json.loads(request.body.decode('utf-8'))

        # 直接返回JSON响应
        return JsonResponse({
            'success': True,
            'data': selected_data_array,
        })
    else:
        # 如果不是POST请求，返回错误状态
        return JsonResponse({'success': False}, status=400)

def show_selected_data(request):
    data = None
    if request.method == 'GET':
        # 尝试从查询参数中获取数据
        data_string = request.GET.get('data')
        if data_string:
            try:
                # 解码并解析 JSON 数据
                data = json.loads(unquote(data_string))
            except json.JSONDecodeError:
                pass  # 或者你可以设置 data = None 并显示错误消息
    
    # 使用模板渲染数据
    template = loader.get_template('selected_data.html')
    context = {
        'data': data,
    }
    return HttpResponse(template.render(context, request))